package database;
import redis.clients.jedis.Jedis;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class Redis {

    public Redis(String tableName) {
        // 数据库配置
        String mysqlUrl = "jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC";
        String mysqlUser = "root";
        String mysqlPassword = "123456";

        // Redis配置
        String redisHost = "localhost";
        int redisPort = 6379;

        // 连接到MySQL
        try (Connection conn = DriverManager.getConnection(mysqlUrl, mysqlUser, mysqlPassword)) {

            List<String> data = fetchDataFromMysql(conn, tableName);

            // 连接到Redis
            try (Jedis jedis = new Jedis(redisHost, redisPort)) {
                // 将数据导入到Redis
                importDataToRedis(jedis, tableName, data);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    private static List<String> fetchDataFromMysql(Connection conn, String tableName) throws SQLException {
        List<String> dataList = new ArrayList<>();
        // 编写SQL查询所有数据
        String sql = "SELECT * FROM " + tableName;
        try (Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(sql)) {
            while (rs.next()) {
                // 假设所有列都是字符串类型，这里简单将所有列拼接成一个字符串
                StringBuilder rowBuilder = new StringBuilder();
                for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) {
                    rowBuilder.append(rs.getString(i)).append(",");
                }
                String rowData = rowBuilder.toString();
                dataList.add(rowData.substring(0, rowData.length() - 1)); // 移除尾部逗号
            }
        }
        return dataList;
    }

    private static void importDataToRedis(Jedis jedis, String tableName, List<String> dataList) {
        for (String data : dataList) {
            // 第一个字段是Eid
            String[] fields = data.split(",");
            if (fields.length > 0) {
                String Eid = fields[0]; // 获取Eid值，根据实际情况调整索引

                // 使用Eid和表名构造Redis的key
                String redisKey = Eid;

                // 将每行数据存储为Redis的String
                jedis.set(redisKey, data);
            }
        }
    }
    public static void main(String[] args) {
        new Redis("tb_employee");
        Jedis jedis = new Jedis("localhost", 6379);
        String type = jedis.type("yg10004");
        System.out.println("The type of 'passwords' is: " + type);
        System.out.print("成功添加");
    }
    }


